package com.COMP3111H.project;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity {
	final int HELP = 0;
	private SharedPreferences dhj;

	private ProgressDialog progDialog;
	private ProgressThread progThread;

	final int THREAD_LOGIN = 0;
	final int THREAD_FORGETPWD = 1;
	Button menu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		dhj = this.getSharedPreferences("bookwarm", MODE_PRIVATE);

		Button back = (Button) findViewById(R.id.b_Login_Back);
		back.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();

			}
		});

		Button login = (Button) findViewById(R.id.b_Login_Login);
		login.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				EditText usernameView = (EditText) findViewById(R.id.et_Login_Username);
				EditText passwordView = (EditText) findViewById(R.id.et_Login_Password);

				String username = usernameView.getText().toString()
						.toLowerCase();
				String password = passwordView.getText().toString()
						.toLowerCase();

				if (username.matches("") || password.matches("")) {
					Toast.makeText(Login.this, "Missing Input",
							Toast.LENGTH_SHORT).show();
				} else {
					showDialog(0);
					progThread = new ProgressThread(handlerLogin, username,
							password, THREAD_LOGIN);
					progThread.start();
				}
			}
		});

		Button forget = (Button) findViewById(R.id.ForgetPassword);
		forget.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				EditText usernameView = (EditText) findViewById(R.id.et_Login_Username);
				String username = usernameView.getText().toString()
						.toLowerCase();
				if (username.matches("")) {
					Toast.makeText(Login.this, "Please input your username.",
							Toast.LENGTH_SHORT).show();
				} else {
					showDialog(0);
					progThread = new ProgressThread(handlerForgetPwd, username,
							"", THREAD_FORGETPWD);
					progThread.start();

				}
			}
		});
		menu = (Button) findViewById(R.id.login_menu);
		menu.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				 String[] choices={"Home","Help","Cancel"};  
				             AlertDialog dialog = new AlertDialog.Builder(Login.this)  
				                     // .setIcon(android.R.drawable.btn_star)  
				                      .setTitle("Menu")  
				                      .setItems(choices, onselect_logged).create();  
				             dialog.show();  
			}
		});
	}
	
	OnClickListener onselect_logged = new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			Intent myIntent;
			switch (which) {
			case 0:
				myIntent = new Intent(Login.this, Home.class);
				startActivity(myIntent);
				break;
			case 1:
				myIntent = new Intent(Login.this, Help.class);
				startActivity(myIntent);
				break;
			case 2:
				dialog.dismiss();
				break;
			}
		}
	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0: // Spinner
			progDialog = new ProgressDialog(this);
			progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDialog.setMessage("Loading...");

			return progDialog;
		default:
			return null;

		}
	}

	final Handler handlerLogin = new Handler() {
		public void handleMessage(Message msg) {
			removeDialog(0);
			int result = msg.getData().getInt("login");

			// Check input: charactors invalid
			if (result == -2) {
				Toast.makeText(
						Login.this,
						"There are special characters that are not allowed in your request",
						Toast.LENGTH_SHORT).show();
			}
			// Login: success
			else if (result == 1) {

				Intent it = new Intent();
				it.putExtra("loginresult", "OK");

				// it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				setResult(Activity.RESULT_OK, it);
				finish();
			}
			// Login: Username and password not match
			else if (result == 0) {

				Toast.makeText(
						Login.this,
						"Username and password do not match. Please try again.",
						Toast.LENGTH_SHORT).show();
			}
			// Login: Network error
			else if (result == -1) {
				String returnResult = msg.getData().getString("returnResult");
				Log.v("Bookwarm", "error+" + returnResult);
				Toast.makeText(Login.this, "Network Error.", Toast.LENGTH_SHORT)
						.show();
			}

		}
	};

	final Handler handlerForgetPwd = new Handler() {
		public void handleMessage(Message msg) {
			removeDialog(0);
			String returnResult = msg.getData().getString("returnResult");
			if (returnResult.contains("reset_password_successful")) {
				Toast.makeText(
						Login.this,
						"Success. Please check your email for the new password and reset your password.",
						Toast.LENGTH_SHORT).show();
				finish();
			} else if (returnResult.contains("reset_password_failed")) {
				Toast.makeText(Login.this,
						"Password reset failed. Please try again later.",
						Toast.LENGTH_SHORT).show();
			} else if (returnResult.contains("no_user_found")) {
				Toast.makeText(Login.this, "Such username does not exist.",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(Login.this, "Network error", Toast.LENGTH_SHORT)
						.show();
			}
		}
	};

	private class ProgressThread extends Thread {
		Handler mHandler;
		String username;
		String password;
		int typeThread;

		ProgressThread(Handler h, String name, String pwd, int type) {
			mHandler = h;
			username = name;
			password = pwd;
			typeThread = type;
		}

		@Override
		public void run() {
			if (typeThread == THREAD_LOGIN) {
				Message msg = mHandler.obtainMessage();
				Bundle b = new Bundle();

				SharedPreferences.Editor dhjEditor = dhj.edit();
				dhjEditor.putString("username", username);
				dhjEditor.putString("password", password);

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("username", username));
				params.add(new BasicNameValuePair("password", password));

				if (!NetworkUtility.inputCheck(username)
						|| !NetworkUtility.inputCheck(password)) {
					b.putInt("login", -2);
				} else {

					String returnResult = NetworkUtility
							.sendHTTP(params,
									"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/login.jsp");
					b.putString("returnResult", returnResult);

					if (returnResult.contains("user_logged_in")) {
						dhjEditor.putString("username", username);
						dhjEditor.putString("password", password);
						dhjEditor.commit();
						b.putInt("login", 1);

					} else if (returnResult.contains("no_user_found")) {
						b.putInt("login", 0);

					} else {
						b.putInt("login", -1);

					}

					msg.setData(b);
					mHandler.sendMessage(msg);

				}
			} else if (typeThread == THREAD_FORGETPWD) {
				Message msg = mHandler.obtainMessage();
				Bundle b = new Bundle();

				List<NameValuePair> params = new ArrayList<NameValuePair>(1);
				params.add(new BasicNameValuePair("username", username));
				// TODO
				String returnResult = NetworkUtility
						.sendHTTP(
								params,
								"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/account_info_reset_password.jsp");

				b.putString("returnResult", returnResult);
				msg.setData(b);
				mHandler.sendMessage(msg);

			}
		}
	}
}
